<?php
declare (strict_types = 1);
/**
 * 素材模型
 */
namespace app\common\model;

class PgmInfo extends BaseModel
{
    // 设置当前模型对应的完整数据表名称
    protected $table = 't_pgm_info';

    public function matTypeHasOne()
    {
        return $this->hasOne(MatType::class, 'mat_type_id', 'pgm_type');
    }

    public function userHasOne()
    {
        return $this->hasOne(Admin::class, 'id', 'creator');
    }

    public function pgmlibList($where = [], $offset = 1, $length = 20, $ordername="pgm_id", $order="desc")
    {
        $field = '*';
        $whereMat = [];
        $userwhere = [];

        $list = self::with([
            'matTypeHasOne' => function ($query) use ($whereMat) {
                $query->withField(['mat_type_id','mat_type_name'])->hidden(['mat_type_id'])->where($whereMat);
            },
            'userHasOne' => function($query) use ($userwhere) {
                $query->withField(['id','truename'])->hidden(['id'])->where($userwhere);
            }
        ])->field($field)->where($where)->limit(($offset) * $length, $length)->order([$ordername => $order])->select()->toArray();

        foreach($list as $k =>$v) {
            if($v['matTypeHasOne'] != null) {
                $list[$k]['pgm_type_name'] = $v['matTypeHasOne']['mat_type_name'];                               
            } else {
                $list[$k]['pgm_type_name'] = null;
            }

            if(isset($v['userHasOne']) && $v['userHasOne']!= null) {
                $list[$k]['truename'] = $v['userHasOne']['truename']; 
            } else {
                $list[$k]['truename'] = null;
            }
            unset($list[$k]['matTypeHasOne']);
            unset($list[$k]['userHasOne']);
        }  

        $count = self::where($where)->count('pgm_id');

        return [
            'list'  => $list,
            'total' => $count,
            'pagenum' => $offset
        ];        
    }
}
